import { reqOrderAddress,reqOrderInfo, reqBuyNowGoods, reqSumbmitOrder,reqPrePayInfo,reqPayStatus } from '@/api/orderpay'
import { formatTime } from '@/utils/formatTime'
import Schema from 'async-validator'

const app = getApp()

Page({
  data: {
    buyName: '', // 订购人姓名
    buyPhone: '', // 订购人手机号
    deliveryDate: '选择送达日期', // 期望送达日期
    blessing: '', // 祝福语
    show: false, // 期望送达日期弹框
    minDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    orderAddress:{}, //收获地址
    orderInfo:{}
  },

  // 期望送达日期
  onShowDateTimerPopUp() {
    this.setData({
      show: true
    })
  },

  // 期望送达日期确定按钮
  onConfirmTimerPicker(event) {
    const timeRes = formatTime(new Date(event.detail))
    this.setData({
      show: false,
      deliveryDate: timeRes
    })
  },

  // 期望送达日期取消按钮
  onCancelTimePicker() {
    this.setData({
      show: false
    })
  },

  // 跳转到收货地址
  toAddress() {
    wx.navigateTo({
      url: '/modules/settingModule/pages/address/list/index'
    })
  },
  async getAddress(){
    //
    const addressId = app.globalData.address.id
    if(addressId){
      this.setData({
        orderAddress: app.globalData.address
      })
      return
    }
    //
    const { data : orderAddress } = await reqOrderAddress()
    this.setData({
      orderAddress
    })
  },
  onShow(){
    this.getAddress()
    this.getOrderInfo()
  },
  // 弹框关闭
  onClose() {},
  //
  onUnload(){
    app.globalData.address = {}
  },
  async getOrderInfo(){
    const { goodsId, blessing } = this.data

    const { data: orderInfo } = goodsId ? await reqBuyNowGoods({ goodsId, blessing } ) : await reqOrderInfo()

    const orderGoods = orderInfo.cartVoList.find( (item) => item.blessing !== '' )


    this.setData({
      orderInfo,
      blessing: !orderGoods ? "" : orderGoods.blessing
    })
  },
  onLoad(options){
    this.setData({
      ...options
    })
  },
  async submitOrder(){
    const {buyName, buyPhone, deliveryDate, blessing, orderAddress, orderInfo} = this.data
    const params = {
      buyName,
      buyPhone,
      cartList: orderInfo.cartVoList,
      deliveryDate,
      remarks: blessing,
      userAddressId: orderAddress.id
    }
    const { valid } = await this.validatePerson(params)
    if(!valid) return
    //创建平台订单
    const res = await reqSumbmitOrder(params)
    //console.log(res)
    if(res.code === 200){
      this.orderNo = res.data 
      //获取预付单信息、支付参数
      this.advancePay()
    }
  },
  async advancePay(){
    try {
      const payParams = await reqPrePayInfo(this.orderNo)
      if(payParams.code === 200){
        const payInfo = await wx.requestPayment(payParams.data)
        console.log(payInfo)
        if(payInfo.errMsg === 'requestPayment:ok'){
          const payStatus = reqPayStatus(this.orderNo)
          if(payStatus.code === 200){
            wx.redirectTo({
              url: '/modules/orderPayModule/pages/order/list/list',
              success: () => {
                wx.toast({title:'支付成功', icon: 'success'})
              }
            })
          }
        }
      } 
    } catch (error) {
      console.log(error)
      wx.toast({title:'支付失败', icon:'error'})
    } 
  },
  validatePerson(params){
    // 验证订购人，是否只包含大小写字母、数字和中文字符
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'
    // 验证手机号
    const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'
    const rules = {
      userAddressId:[
        { required: true, message: '请输入收货地址~' }
      ],
      buyName: [
        { required: true, message: '请输入收货人姓名~' },
        { pattern: nameRegExp, message: '收货人姓名不合法~' }
      ],
      buyPhone: [
        { required: true, message: '请输入收货人手机号' },
        { pattern: phoneReg, message: '手机号不合法' }
      ],
      deliveryDate: { required: true, message: '请选择送达日期' }
    }
    const validator = new Schema(rules)
    // 调用实例方法对数据进行验证
    // 注意：我们希望将验证结果通过 Promsie 的形式返回给函数的调用者
    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          // 如果验证失败，需要给用户进行提示
          wx.toast({
            title: errors[0].message,
            mask: false
          })
          resolve({ valid: false })
        } else {
          resolve({ valid: true })
        }
      })
    })
  },
})
